package com.ruoyi.web.core.config;

import com.baomidou.mybatisplus.annotation.IEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * 自定义枚举转换器（直接抄StringToEnumConverterFactory）
 *
 * @author mx
 */
public final class MyEnumConverterFactory implements ConverterFactory<String, IEnum> {

    @Override
    public <T extends IEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum(targetType);
    }

    private static class StringToEnum<T extends IEnum> implements Converter<String, T> {

        private final Class<T> enumType;

        public StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) {
            if (source.isEmpty()) {
                // It's an empty enum identifier: reset the enum value to null.
                return null;
            }
            for (T enumObject : enumType.getEnumConstants()) {
                // 默认项目中所有Enum都实现了IEnum，那么必然有getValue()
                if (source.equals(String.valueOf(enumObject.getValue()))) {
                    return enumObject;
                }
            }
            return null;
        }
    }

}

